<template>
    <div class="white-box">
        <cellTip
            tip="当前只展示顶级网点，其余网点可通过检索条件【上级网点】进行查询"
        />
        <div>
            <el-button
                v-hasPermi="['enttp:outlets:add']"
                class="table-mb"
                type="primary"
                @click="onClickAdd"
                >添加网点</el-button
            >
        </div>

        <div class="task-one">
            <div class="task-one__item">
                <span class="task-one__label">网点名称：</span>
                <el-input
                    placeholder="请输入网点名称"
                    v-model="state.outletsName"
                    @keyup.enter.native="handleSearch"
                    clearable
                >
                </el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">联系人员：</span>
                <el-input
                    placeholder="请输入网点联系人员"
                    v-model="state.outletsMember"
                    @keyup.enter.native="handleSearch"
                    clearable
                >
                </el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">联系电话：</span>
                <el-input
                    placeholder="请输入网点联系电话"
                    v-model="state.outletsPhone"
                    @keyup.enter.native="handleSearch"
                    clearable
                >
                </el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">所选区域：</span>
                <el-input
                    placeholder="请输入网点省市区地址"
                    v-model="state.wardAddress"
                    @keyup.enter.native="handleSearch"
                    clearable
                >
                </el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">详细地址：</span>
                <el-input
                    placeholder="请输入网点详细地址"
                    v-model="state.fullAddress"
                    @keyup.enter.native="handleSearch"
                    clearable
                >
                </el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">服务类型：</span>
                <el-select
                    v-model="state.serviceRangeType"
                    placeholder="请选择服务范围类型"
                    clearable
                >
                    <el-option
                        v-for="item in state.outletsTypeList"
                        :key="item.memberKey"
                        :label="item.memberName"
                        :value="item.memberKey"
                    />
                </el-select>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">上级网点：</span>
                <el-tree-select
                    v-model="state.parentTreeCode"
                    :data="state.outletsOptions"
                    filterable
                    check-strictly
                    placeholder="请选择上级网点"
                    clearable
                    :props="{ value: 'treeCode', label: 'outletsName' }"
                />
            </div>
            <div class="task-one__item">
                <span class="task-one__label">网点状态：</span>
                <el-select
                    v-model="state.status"
                    placeholder="请选择状态"
                    clearable
                >
                    <el-option
                        v-for="item in state.statusList"
                        :key="item.memberKey"
                        :label="item.memberName"
                        :value="item.memberKey"
                    />
                </el-select>
            </div>
            <div class="task-one__btn clearfix">
                <el-button
                    type="primary"
                    :loading="loading"
                    icon="Search"
                    @click="handleSearch"
                    >搜索</el-button
                >
            </div>
        </div>

        <div>
            <el-button
                class="table-mb"
                v-hasPermi="['enttp:outlets:del']"
                @click="onClickDel()"
                >批量删除网点</el-button
            >
        </div>

        <el-table
            class="table-mb"
            v-loading="loading"
            :data="arr_data"
            row-key="sid"
            :header-cell-style="{
                background: '#F5F7FA',
                textAlign: 'center',
            }"
            :cell-style="
                ({ column }) => {
                    return {
                        textAlign:
                            column.className === 'operation-nav'
                                ? 'left'
                                : 'center',
                        paddingLeft:
                            column.className === 'operation-nav' ? '25px' : '0',
                    };
                }
            "
            border
            element-loading-background="rgba(255, 255, 255, 0.6)"
            @selection-change="selectionChange"
            @sort-change="sortChange"
        >
            <el-table-column
                type="selection"
                width="55"
                v-hasPermi="['enttp:outlets:del']"
            />
            <el-table-column
                prop="outletsName"
                label="网点名称"
                min-width="150"
                fixed="left"
            >
            </el-table-column>
            <el-table-column
                label="网点位置"
                min-width="200"
                :show-overflow-tooltip="{
                    'popper-class': 'max-w-800',
                }"
            >
                <template #default="{ row }">
                    {{ row.wardAddress + row.fullAddress }}
                </template>
            </el-table-column>
            <el-table-column label="Logo" min-width="150">
                <template #default="{ row }">
                    <Image :src="row.logoUrl" />
                </template>
            </el-table-column>
            <el-table-column
                prop="outletsMember"
                label="联系人姓名"
                min-width="150"
            >
            </el-table-column>
            <el-table-column
                prop="outletsPhone"
                label="联系人电话"
                min-width="120"
            ></el-table-column>
            <el-table-column
                label="服务范围类型"
                min-width="160"
                sortable="custom"
            >
                <template #default="{ row }">
                    {{
                        dictStore.getDictMemberName(
                            "outlets_type",
                            row.serviceRangeType
                        )
                    }}
                </template>
            </el-table-column>
            <el-table-column
                prop="status"
                label="状态"
                min-width="100"
                sortable="custom"
            >
                <template #default="{ row }">
                    {{ dictStore.getDictMemberName("data_status", row.status) }}
                </template>
            </el-table-column>
            <el-table-column
                prop="created"
                label="创建时间"
                min-width="160"
                sortable="custom"
            ></el-table-column>
            <el-table-column
                label="操作"
                width="200"
                class-name="operation-nav"
                fixed="right"
            >
                <template #default="{ row }"
                    ><MoreBtn
                        :buttons="[
                            {
                                props: {
                                    onClick: () => onClickDetails(row.sid),
                                    'v-hasPermi': ['enttp:outlets:query'],
                                },
                                text: '详情',
                            },
                            {
                                props: {
                                    onClick: () => changeStatus(row.sid),
                                    'v-hasPermi': ['enttp:outlets:update'],
                                },
                                text: ['停用', '启用'][row.status],
                            },
                            {
                                props: {
                                    onClick: () => onClickEdit(row.sid),
                                    'v-hasPermi': ['enttp:outlets:edit'],
                                },
                                text: '修改',
                            },
                            {
                                props: {
                                    onClick: () => onClickDel(row.sid),
                                    'v-hasPermi': ['enttp:outlets:del'],
                                },
                                text: '删除',
                            },
                        ]"
                    />
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            background
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="pageSizeNum"
            :total="totalNums"
            layout="slot, sizes, prev, pager, next, jumper"
        >
            <span class="color-#606266"
                >共&nbsp;{{
                    totalNums >= 100 * pageSize
                        ? `${100 * pageSize}+`
                        : totalNums
                }}&nbsp;条</span
            >
        </el-pagination>
    </div>

    <el-drawer
        v-model="state.showDetail"
        title="网点详情"
        @closed="destroyMap"
        size="540"
    >
        <template v-if="detail">
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">网点名称</el-col>
                <el-col :span="18">{{ detail.outletsName }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">网点位置</el-col>
                <el-col :span="18">{{
                    detail.wardAddress + detail.fullAddress
                }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">网点Logo</el-col>
                <el-col :span="18"
                    ><Image :size="100" :src="detail.logoUrl"
                /></el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">联系人姓名</el-col>
                <el-col :span="18">{{ detail.outletsMember }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">联系人电话</el-col>
                <el-col :span="18">{{ detail.outletsPhone }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">服务范围类型</el-col>
                <el-col :span="18">{{
                    dictStore.getDictMemberName(
                        "outlets_type",
                        detail.serviceRangeType
                    )
                }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">网点服务范围</el-col>
                <el-col :span="18">
                    <template v-if="detail.serviceRangeType === 0">
                        <p
                            v-for="(item, index) in detail.regionDistrictCode"
                            :key="index"
                        >
                            {{ item.fullName }}
                        </p>
                    </template>
                    <template v-else>
                        <TencentMap
                            v-if="state.showMap"
                            ref="mapRef"
                            :search="false"
                            map-class="h-200"
                            :multiOptions="{
                                polygon: true,
                                circle: true,
                            }"
                            :marker-geometries="detail.marker"
                            :polygon-geometries="detail.polygon"
                            :circle-geometries="detail.circle"
                        />
                    </template>
                </el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">网点员工</el-col>
                <el-col :span="18">
                    <el-table
                        :data="detail.users"
                        row-key="sid"
                        :header-cell-style="{
                            background: '#F5F7FA',
                            textAlign: 'center',
                        }"
                        :cell-style="
                            ({ column }) => {
                                return {
                                    textAlign:
                                        column.className === 'operation-nav'
                                            ? 'left'
                                            : 'center',
                                    paddingLeft:
                                        column.className === 'operation-nav'
                                            ? '25px'
                                            : '0',
                                };
                            }
                        "
                        border
                        size="small"
                        max-height="200"
                        element-loading-background="rgba(255, 255, 255, 0.6)"
                    >
                        <el-table-column
                            prop="nickName"
                            label="昵称"
                        ></el-table-column>
                        <el-table-column label="头像">
                            <template #default="{ row }">
                                <Image :size="30" :src="row.avatar" />
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">状态</el-col>
                <el-col :span="18">{{
                    dictStore.getDictMemberName("data_status", detail.status)
                }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">创建时间</el-col>
                <el-col :span="18">{{ detail.created }}</el-col>
            </el-row>
        </template>
    </el-drawer>
</template>

<script setup>
import {
    inject,
    reactive,
    onMounted,
    onActivated,
    toRefs,
    ref,
    nextTick,
} from "vue";
import { useRouter } from "vue-router";
import OneLoad from "@mixins/one-load";
import MoreBtn from "@/components/MoreBtn.vue";
import { ElMessageBox } from "element-plus";
import Image from "@/components/Image.vue";
import {
    getOutlets,
    getOutletDetail,
    delOutlets,
    changeOutletStatus,
    getOutletElectronics,
    getOutletDistrictCodes,
    getOutletsAll,
    getOutletUsers,
} from "@/apis/outlet/outlet";
import TencentMap from "@/components/TencentMap.vue";
import cellTip from "@/components/cell-tip.vue";
import { useDictStore } from "@stores/dict.js";

const dictStore = useDictStore();
dictStore.getDictMembers("data_status").then((res) => (state.statusList = res));
dictStore
    .getDictMembers("outlets_type")
    .then((res) => (state.outletsTypeList = res));

const router = useRouter();
const $message = inject("$message");

const mapRef = ref(null);
const state = reactive({
    statusList: [],
    outletsTypeList: [],
    ascended: false,
    sortFieldName: null,
    outletsName: null,
    outletsMember: null,
    outletsPhone: null,
    fullAddress: null,
    address: null,
    parentTreeCode: null,
    serviceRangeType: null,
    wardAddress: null,
    status: null,
    sidList: [],
    showDetail: false,
    showMap: false,
    detail: null,
    outletsOptions: [],
});

const { detail } = toRefs(state);

onActivated(() => {
    pubParams(getList);
    getOutletsOptions();
});

// 获取所有网点
const getOutletsOptions = async () => {
    const res = await getOutletsAll();
    if (res.data.code == 200) {
        state.outletsOptions = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

/**
 * minxin列表加载
 */
const {
    loading,
    arr_data,
    pubRefreshParams,
    pubParams,
    page,
    pageSize,
    getdata,
    pageSizeNum,
    totalNums,
    openPaging,
} = OneLoad();

openPaging(getList);

function getList() {
    getdata(
        getOutlets({
            current: page.value,
            size: pageSize.value,
            ascended: state.ascended,
            sortFieldName: state.sortFieldName,
            outletsName: state.outletsName,
            outletsMember: state.outletsMember,
            outletsPhone: state.outletsPhone,
            fullAddress: state.fullAddress,
            wardAddress: state.wardAddress,
            parentTreeCode: state.parentTreeCode,
            address: state.address,
            serviceRangeType: state.serviceRangeType,
            status: state.status,
        })
    );
}

// 搜索
const handleSearch = () => {
    pubRefreshParams(getList);
};

// 跳转到新增页
const onClickAdd = () => {
    router.push({ name: "OutletsAdd" });
};

// 排序
const sortChange = (e) => {
    const { property, order } = e.column;
    state.ascended = order === "ascending";
    state.sortFieldName = order ? property : null;
    pubRefreshParams(getList);
};

// 点击修改按钮
const onClickEdit = (sid) => {
    sid &&
        router.push({
            name: "OutletsEdit",
            query: {
                sid,
            },
        });
};

// 跳转详情
const onClickDetails = async (sid) => {
    state.showDetail = true;
    state.showMap = true;
    state.detail = null;
    await getDetails(sid);

    switch (state.detail.serviceRangeType) {
        case 0:
            getRegionCode();
            break;
        case 10:
            nextTick(() => {
                mapRef.value.initMap();
                state.detail.marker = [];
                state.detail.polygon = [];
                state.detail.circle = [];
                loadMapInfo();
            });
            break;
    }
    state.detail.users = [];
    getStaff();
};

const getDetails = async (sid) => {
    const res = await getOutletDetail({ sid });
    if (res.data.code == 200) {
        state.detail = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const destroyMap = () => {
    state.showMap = false;
};

const loadMapInfo = async () => {
    const { serviceRangeType, latitude, longitude } = state.detail;
    const position = new TMap.LatLng(latitude, longitude);
    state.detail.marker = [{ position }];
    mapRef.value.panTo(position);
    const [polygon, circle] = await getElectronicFence();
    state.detail.polygon = polygon;
    state.detail.circle = circle;
    // switch (serviceRangeType) {
    //     case 0:
    //         // 按区域
    //         getRegionCode();
    //         break;
    //     case 10:
    //         // 按电子围栏
    //         getElectronicFence();
    //         break;
    // }
};

// 根据网点SID查询网点服务的行政区划编码
const getRegionCode = async () => {
    const res = await getOutletDistrictCodes({ sid: state.detail.sid });
    if (res.data.code == 200) {
        state.detail.regionDistrictCode = res.data.data;
        // 获取行政区边界 绘制区域高亮 接口只能查询单个区域的轮廓点串
        /*const keyword = state.detail.regionDistrictCode.reduce(
            (pre, cur, index) => {
                pre = (index === 0 ? "" : ",") + pre + cur.regionDistrictCode;
                return pre;
            },
            ""
        );
        const district = new TMap.service.District({
            polygon: 2
        });
        const result = await district.search({
            keyword: keyword,
        });
        if (result?.result?.length) {
            state.detail.polygon = result.result[0].reduce((pre, cur) => {
                cur.polygon && pre.push({ paths: cur.polygon });
                return pre;
            }, []);
        }
        console.log(result);*/
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 根据网点SID查询网点服务的电子围栏坐标
const getElectronicFence = async () => {
    const res = await getOutletElectronics({ sid: state.detail.sid });

    if (res.data.code == 200) {
        const polygon = [];
        const circle = [];
        res.data.data.forEach((item) => {
            if (item.electronicfenceType === 0) {
                // 多边形
                polygon.push({
                    paths: item.polygonCoordinate.map(
                        (item) => new TMap.LatLng(item[0], item[1])
                    ),
                });
            } else {
                // 圆形
                circle.push({
                    center: new TMap.LatLng(
                        item.circleCoordinate[0],
                        item.circleCoordinate[1]
                    ),
                    radius: Number(item.circleRadius),
                });
            }
        });
        return [polygon, circle];
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 根据网点sid查询绑定的员工
const getStaff = async () => {
    const res = await getOutletUsers({ sid: state.detail.sid });
    if (res.data.code == 200) {
        state.detail.users = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 切换状态
const changeStatus = async (sid) => {
    const res = await changeOutletStatus({ sid });
    if (res.data.code == 200) {
        $message({ message: "操作成功", type: "success" });
        pubParams(getList);
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 选中项改变
const selectionChange = (e) => {
    state.sidList = e.map((item) => item.sid);
};

// 删除
const onClickDel = async (sid) => {
    if (sid) {
        state.sidList = [sid];
    }
    if (!state.sidList.length) {
        return $message({ message: "请先勾选要删除的数据", type: "warning" });
    }
    await ElMessageBox.confirm("确定删除网点吗？");
    const res = await delOutlets({ sidList: state.sidList });
    if (res.data.code == 200) {
        $message({ message: "删除成功", type: "success" });
        pubParams(getList);
        getOutletsOptions();
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};
</script>

<style lang="less" scoped></style>
